<template>
  <el-drawer v-model="isShow" :destroy-on-close="true">
    <TreeFilter
      ref="treeFilterRef"
      :multiple="true"
      label="orgName"
      :title="$t('message.orgInfo.title')"
      :check-strictly="props.checkStrictly"
      :default-value="props.defaultValue"
      :data="orgTree"
      :default-expand="props.defaultExpand"
      @change="handleCheckChange"
    >
    </TreeFilter>
    <template #footer>
      <div class="footer-buttons">
        <el-button @click="isShow = false">{{ $t("message.commonBtn.cancel") }}</el-button>
        <el-button type="primary" @click="handleSubmit">{{ $t("message.commonBtn.submit") }}</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script setup lang="ts" name="OrgSelector">
import { SysOrg, SysRole } from "@/api-services/models/system";
import TreeFilter from "@/components/TreeFilter/index.vue";
import { useOrgStore } from "@/stores/modules/org";
import roleApi from "@/api-services/apis/system/roleApi";
import { feature } from "@/utils/axios-utils";
import { useI18n } from "vue-i18n";
import { NotificationError, NotificationSuccess } from "@/utils/notification";
const { t } = useI18n();
const treeFilterRef = ref<InstanceType<typeof TreeFilter> | null>(null);
const isShow = ref(false);
const orgTree = ref<SysOrg.OrgSimpleInfo[]>([]);
// 接收父组件参数并设置默认值
interface OrgSelectorProps {
  defaultValue?: any; // 默认选中的值 ==> 非必传
  defaultExpand?: boolean; //是否展开
  checkStrictly?: boolean; //在显示复选框的情况下，是否严格的遵循父子不互相关联的做法，默认为 false
  roleInfo: SysRole.SysRoleInfo;
}
const props = ref<OrgSelectorProps>({
  checkStrictly: false,
  defaultExpand: false,
  roleInfo: {}
});

const checkOrgIdList = ref<number[]>();
const handleCheckChange = (val: number[]) => {
  checkOrgIdList.value = val;
};

const orgSelector = async (param: OrgSelectorProps) => {
  isShow.value = true;
  props.value = param;
  const orgStore = useOrgStore();
  orgTree.value = await orgStore.orgSelectorGet;
  let ownOrg = await roleApi.getOwnOrg({ id: props.value.roleInfo.id! });
  props.value.defaultValue = ownOrg.data.data;
};

const handleSubmit = async () => {
  const param = {
    id: props.value.roleInfo.id!,
    orgList: checkOrgIdList.value
  };
  const [err] = await feature(roleApi.grantRoleOrgs(param));
  if (err) {
    NotificationError(err.message);
  } else {
    NotificationSuccess(t("message.roleAlter.grantOrgSuccess"));
    isShow.value = false;
  }
};
defineExpose({ orgSelector });
</script>
<style scoped lang="scss">
.footer-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-start;
}

/* 在这里添加您的自定义样式 */
.filter {
  width: 80%; /* 修改宽度为 300px */
}
</style>
